package com.rd.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;

// redis 唯一id生成策略
@Component
public class RedisIdWorker {

    // 开始时间戳 (以某个时间段)
    private static final long BEGIN_TIMESTAMP = 1640995200L;

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    public long nextId(String keyPrefix){

        // 1、生成时间戳
        //1.1、获取当前时间秒数
        LocalDateTime now = LocalDateTime.now();
        long nowSeconds = now.toEpochSecond(ZoneOffset.UTC);
        //1.1、获取当前时间戳
        long curTimestamp = nowSeconds - BEGIN_TIMESTAMP;
        // 2、生成序列号
        String date = now.format(DateTimeFormatter.ofPattern("yyyy:MM:dd"));
        // 该key的值自增
        long incr = stringRedisTemplate.opsForValue().increment("incr:" + keyPrefix + ":" + date);

        ///3、拼接并返回
        // curTimestamp 左移 32 ，这样空出32位
        // 然后在 或上 incr ,这样得到64位ID
        return curTimestamp << 32 | incr;
    }

    public static void main(String[] args) {
        LocalDateTime time = LocalDateTime.of(2022,1,1,0,0,0);
        long seconds = time.toEpochSecond(ZoneOffset.UTC);
        System.out.println(seconds);
    }
}
